<?php
/*
 * Created on 2013-2-6
 *
 */
include_once dirname(__FILE__)."/basedao.php";
include_once dirname(__FILE__)."/usersdao.php";
include_once dirname(__FILE__)."/rolesdao.php";
include_once dirname(__FILE__)."/../objects/role.php";
include_once dirname(__FILE__)."/../objects/user.php";
class Membership extends BaseDAO{
	/**
	 * 添加用户角色
	 */
	public function insertUserToRole($user_id, $role_id){
		$this->getConn()->query("LOCK TABLES userinroles WRITE");
		$sqlstr = "INSERT INTO userinroles(user_id, role_id) VALUES(?,?)";
		$stmt = $this->getStmt();
		$stmt->prepare($sqlstr);
		$stmt->bind_param("ii",
							$user_id,
							$role_id);
		$stmt->execute();
		$stmt->close();
		$this->getConn()->query("UNLOCK TABLES");
	}
	/**
	 * 移除用户角色
	 */
	public function deleteUserFromRole($user_id, $role_id){
		$this->getConn()->query("LOCK TABLES userinroles WRITE");
		$sqlstr = "DELETE FROM userinroles WHERE user_id=? and role_id=?";
		$stmt = $this->getStmt();
		$stmt->prepare($sqlstr);
		$stmt->bind_param("ii",
							$user_id,
							$role_id);
		$stmt->execute();
		$stmt->close();
		$this->getConn()->query("UNLOCK TABLES");
	}
	/**
	 * 判断用户是否属于某角色
	 */
	public function isUserInRole($user_id, $role_id){
		$this->getConn()->query("LOCK TABLES userinroles READ");
		$sqlstr = "SELECT user_id, role_id FROM userinroles WHERE user_id=? and role_id=?";
		$stmt = $this->getStmt();
		$stmt->prepare($sqlstr);
		$stmt->bind_param("ii",
							$user_id,
							$role_id);
		$stmt->execute();
		$stmt->bind_result($user_id, $role_id);
		$stmt->fetch();
		$stmt->close();
		$this->getConn()->query("UNLOCK TABLES");
		return $user_id != null && $role_id != null;
	}
	/**
	 * 取得用户的所有角色
	 */
	public function getAllRolesOfUser($user_id){
	 	$roles = array();
		$this->getConn()->query("LOCK TABLES userinroles READ");
		$sqlstr = "SELECT role_id FROM userinroles WHERE user_id=?";
		$stmt = $this->getStmt();
		$stmt->prepare($sqlstr);
		$stmt->bind_param("i",
							$user_id);
		$stmt->execute();
		$stmt->bind_result($role_id);
		$rolesdao = new RolesDAO();
		while($stmt->fetch()){
			$role = $rolesdao->getRoleInfoById($role_id);
			array_push($roles,$role);
		}
		$stmt->close();
		$this->getConn()->query("UNLOCK TABLES");
		return $roles;
	}
	/**
	 * 取得属于角色的所有用户
	 */
	public function getAllUsersInRole($role_id){
	 	$users = array();
		$this->getConn()->query("LOCK TABLES userinroles READ");
		$sqlstr = "SELECT user_id FROM userinroles WHERE role_id=?";
		$stmt = $this->getStmt();
		$stmt->prepare($sqlstr);
		$stmt->bind_param("i",
							$role_id);
		$stmt->execute();
		$stmt->bind_result($user_id);
		$userdao = new UserDAO();
		while($stmt->fetch()){
			$user = $userdao->getUserInfoById($user_id);
			array_push($users,$user);
		}
		$stmt->close();
		$this->getConn()->query("UNLOCK TABLES");
		return $users;
	}
}
?>
